<template>
  <div class="page-container">
    <div class="douyin-analyzer">
      <!-- 顶部导航栏 -->
      <div class="nav-header">
        <div class="nav-content">
          <h2>创作助手</h2>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-container">
        <div class="search-content">
          <el-input
              v-model="shareUrl"
              placeholder="请输入抖音分享链接"
              class="share-input"
          >
            <template #append>
              <el-button type="primary" @click="analyzeVideo">
                <el-icon>
                  <Search/>
                </el-icon>
                分析
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 分析结果展示区 -->
      <div v-if="videoData" class="analysis-container">
        <div class="analysis-content">
          <!-- 视频区域 -->
          <div class="content-card">
            <div class="card-header">
              <el-icon>
                <VideoCamera/>
              </el-icon>
              <span>视频内容</span>
            </div>
            <div class="card-body video-container">
              <div v-if="!videoData.videoUrl" class="empty-state">
                <el-button @click="fetchVideo" :loading="videoLoading">
                  获取视频内容
                </el-button>
              </div>
              <video 
                v-else
                controls
                class="video-player"
                :src="videoData.videoUrl"
                @error="handleVideoError"
              ></video>
            </div>
          </div>

          <!-- 评论区域 -->
          <div class="content-card">
            <div class="card-header">
              <el-icon>
                <ChatDotRound/>
              </el-icon>
              <span>热门评论</span>
            </div>
            <div class="card-body">
              <div v-loading="commentsLoading" class="comment-loading-container">
                <div v-if="!comments.length && !commentsLoading" class="empty-state">
                  <el-button @click="fetchComments">获取评论</el-button>
                </div>
                <comment-list v-else-if="!commentsLoading" :comments="comments"/>
              </div>
            </div>
          </div>

          <!-- 视频文案 -->
          <div class="content-card">
            <div class="card-header">
              <el-icon>
                <Document/>
              </el-icon>
              <span>视频文案</span>
            </div>
            <div class="card-body">
              <div v-if="!videoData.script" class="empty-state">
                <el-button @click="fetchScript" :loading="scriptLoading">
                  获取视频文案
                </el-button>
              </div>
              <div v-else class="script-content">{{ videoData.script }}</div>
            </div>
          </div>

          <!-- 二创建议 -->
          <div class="content-card">
            <div class="card-header">
              <el-icon>
                <MagicStick/>
              </el-icon>
              <span>二创建议</span>
            </div>
            <div class="card-body">
              <div v-if="!recreationScript.length" class="empty-state">
                <el-button @click="fetchRecreation" :loading="recreationLoading">
                  获取二创建议
                </el-button>
              </div>
              <div v-else class="recreation-list">
                <div v-for="(item, index) in recreationScript"
                     :key="index"
                     class="recreation-item">
                  <el-icon>
                    <Lightning/>
                  </el-icon>
                  <span>{{ item }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onUnmounted} from 'vue'
import {
  Search, VideoCamera, Document, ChatDotRound,
  MagicStick, Lightning, Refresh
} from '@element-plus/icons-vue'
import CommentList from './CommentList.vue'
import {douyinApi} from '../api/douyin'
import {ElMessage} from 'element-plus'

// 数据响应式引用
const shareUrl = ref('')
const videoData = ref(null)
const comments = ref([])
const recreationScript = ref([])

// 加载状态
const videoLoading = ref(false)
const commentsLoading = ref(false)
const scriptLoading = ref(false)
const recreationLoading = ref(false)

// 获取视频内容
const fetchVideo = async () => {
  if (videoLoading.value) return
  videoLoading.value = true
  
  try {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
    const endpoint = `/api/douyin/video/url?videoId=${videoData.value.id}`
    const fullVideoUrl = `${baseUrl}${endpoint}`
    
    videoData.value = {
      ...videoData.value,
      videoUrl: fullVideoUrl
    }
    
    ElMessage.success('视频加载中...')
  } catch (error) {
    console.error('获取视频失败:', error)
    ElMessage.error('获取视频失败')
  } finally {
    videoLoading.value = false
  }
}

// 获取评论
const fetchComments = async () => {
  if (commentsLoading.value) return
  commentsLoading.value = true
  try {
    const response = await douyinApi.getVideoComments(videoData.value.id)
    if (response?.data) {
      comments.value = response.data.data
      ElMessage.success('评论获取成功')
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  } finally {
    commentsLoading.value = false
  }
}

// 获取视频文案
const fetchScript = async () => {
  if (scriptLoading.value) return
  scriptLoading.value = true

  try {
    const response = await douyinApi.getVideoScript(videoData.value.id)
    if (response?.data?.data) {
      videoData.value = {
        ...videoData.value,
        script: response.data.data
      }
      ElMessage.success('视频文案获取成功')
    } else {
      throw new Error('获取视频文案失败')
    }
  } catch (error) {
    console.error('获取视频文案失败:', error)
    ElMessage.error(error.message || '获取视频文案失败')
  } finally {
    scriptLoading.value = false
  }
}

// 获取二创建议
const fetchRecreation = async () => {
  if (recreationLoading.value) return
  recreationLoading.value = true
  try {
    const response = await douyinApi.getRecreationSuggestions(videoData.value.id)
    if (response?.data) {
      recreationScript.value = response.data
      ElMessage.success('二创建议获取成功')
    }
  } catch (error) {
    console.error('获取二创建议失败:', error)
    ElMessage.error('获取二创建议失败')
  } finally {
    recreationLoading.value = false
  }
}

// 分析视频
const analyzeVideo = async () => {
  if (!shareUrl.value) {
    ElMessage.warning('请输入抖音分享链接')
    return
  }

  try {
    const response = await douyinApi.getVideoId(shareUrl.value)
    // 初始化视频数据
    videoData.value = {
      id: response.data.data, // 这里需要从分享链接中提取
      videoUrl: '',
      script: ''
    }

    ElMessage.success('请选择需要获取的数据')
  } catch (error) {
    console.error('分析视频失败:', error)
    ElMessage.error('分析视频失败')
  }
}

const handleVideoError = (error) => {
  console.error('视频播放错误:', error)
  if (videoData.value?.videoUrl) {
    console.log('视频URL:', videoData.value.videoUrl)
  }
  ElMessage.error('视频播放失败，请重试')
  videoData.value.videoUrl = null
}

// 组件卸载时清理 URL 对象
onUnmounted(() => {
  if (videoData.value?.videoUrl) {
    URL.revokeObjectURL(videoData.value.videoUrl)
  }
})
</script>

<style scoped>
/* 基础布局 */
.page-container {
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  background-color: #f5f7fa;
}

.douyin-analyzer {
  min-height: 100vh;
  min-width: 1200px;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 导航栏样式 */
.nav-header {
  width: 100%;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 15px 0;
}

.nav-content {
  padding: 0 40px;
}

/* 搜索区域样式 */
.search-container {
  width: 100%;
  padding: 20px 40px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.search-content {
  max-width: 800px;
  margin: 0 auto;
}

.share-input {
  width: 100%;
}

/* 分析结果区域 */
.analysis-container {
  flex: 1;
  margin-top: 10px;
}

.analysis-content {
  display: grid;
  grid-template-columns: repeat(4, 280px);
  gap: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  justify-content: center;
  margin: 0 auto;
  max-width: 1200px;
}

/* 卡片样式 */
.content-card {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #eee;
  display: flex;
  flex-direction: column;
  height: 600px;
  overflow: hidden;
  transition: box-shadow 0.3s ease;
}

.content-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #333;
}

.card-header .el-button {
  margin-left: auto;
}

.card-body {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  position: relative;
}

/* 视频容器 */
.video-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #000;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  gap: 12px;
  padding: 20px;
}

.empty-state .el-button {
  margin-top: 12px;
}

/* 评论加载容器 */
.comment-loading-container {
  height: 100%;
  width: 100%;
  min-height: 200px;
}

/* 二创建议列表 */
.recreation-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.recreation-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: background-color 0.2s ease;
}

.recreation-item:hover {
  background: #f0f2f5;
}

/* 美化滚动条 */
.card-body::-webkit-scrollbar {
  width: 6px;
}

.card-body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.card-body::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.card-body::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .douyin-analyzer {
    min-width: 600px;
  }

  .analysis-content {
    grid-template-columns: repeat(2, 280px);
  }
}

@media (max-width: 768px) {
  .douyin-analyzer {
    min-width: 320px;
  }

  .analysis-content {
    grid-template-columns: 280px;
    padding: 10px;
  }

  .analysis-container {
    padding: 10px;
  }
}

/* 添加视频播放器样式 */
.video-player {
  max-width: 100%;
  max-height: 100%;
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style> 